<template>
  <div class="grade-view">
    <el-form :inline="true" class="search-form">
      <el-form-item label="学期">
        <el-select v-model="searchForm.semester" placeholder="选择学期" style="width: 180px" clearable>
          <el-option
              v-for="item in semesterOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级">
        <el-select v-model="searchForm.className" placeholder="选择班级" style="width: 180px" clearable>
          <el-option
              v-for="item in classOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程">
        <el-select v-model="searchForm.courseName" placeholder="选择课程" style="width: 180px" clearable>
          <el-option
              v-for="item in courseOptions"
              :key="item"
              :label="item"
              :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="gradeList" border>
      <el-table-column prop="studentNumber" label="学号" width="120"/>
      <el-table-column prop="studentName" label="姓名" width="100"/>
      <el-table-column prop="className" label="班级" width="120"/>
      <el-table-column prop="courseName" label="课程" width="150"/>
      <el-table-column prop="examType" label="考试类型" width="150"/>
<!--      <el-table-column prop="score" label="成绩" width="100">-->
<!--        <template #default="scope">-->
<!--          <span :class="{ 'fail-score': scope.row.score < 60 }">-->
<!--            {{ scope.row.score }}-->
<!--          </span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="updateTime" label="更新时间" width="180"/>
<!--      <el-table-column prop="operator" label="操作人" width="120"/>-->
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
              size="small"
              @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
              size="small"
              type="primary"
              @click="handleViewGrade(scope.row)"
          >
            查看成绩
          </el-button>
        </template>
      </el-table-column>

    </el-table>

    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />


    <!-- 添加成绩查看对话框 -->
    <el-dialog
        v-model="gradeDialogVisible"
        title="学生成绩详情"
        width="600px"
    >
      <div class="student-info">
        <p><strong>学号：</strong>{{ currentStudent.studentNumber }}</p>
        <p><strong>姓名：</strong>{{ currentStudent.studentName }}</p>
        <p><strong>班级：</strong>{{ currentStudent.className }}</p>
      </div>
      <el-table :data="studentGrades" border stripe>
        <el-table-column prop="courseName" label="课程"/>
        <el-table-column prop="score" label="成绩">
          <template #default="scope">
        <span :class="{ 'fail-score': scope.row.score < 60 }">
          {{ scope.row.score }}
        </span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间"/>
      </el-table>
    </el-dialog>

    <!-- 添加编辑成绩对话框 -->
    <el-dialog
        v-model="editDialogVisible"
        title="编辑学生成绩"
        width="600px"
    >
      <div class="student-info">
        <p><strong>学号：</strong>{{ currentStudent.studentNumber }}</p>
        <p><strong>姓名：</strong>{{ currentStudent.studentName }}</p>
        <p><strong>班级：</strong>{{ currentStudent.className }}</p>
      </div>
      <el-table :data="editGrades" border stripe>
        <el-table-column prop="courseName" label="课程"/>
        <el-table-column prop="score" label="成绩" width="200">
          <template #default="scope">
            <el-input
                v-model="scope.row.score"
                type="number"
                :min="0"
                :max="100"
                @change="validateScore($event, scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitGrades">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import myAxios from "../../../plugins/myAxios.js";

// 搜索表单数据
const searchForm = reactive({
  semester: '',
  className: '',
  courseName: ''
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

const gradeDialogVisible = ref(false)
const currentStudent = ref({})
const studentGrades = ref([])

// 表格数据
const gradeList = ref([])

// 下拉选项数据
const semesterOptions = ref([])

const classOptions = ref([])

const courseOptions = ref([])

// 添加新的响应式变量
const editDialogVisible = ref(false)
const editGrades = ref([])

// 查看学生成绩
const handleViewGrade = async (row) => {
  gradeDialogVisible.value = true
  currentStudent.value = row

  try {
    console.log(row)
    const response = await myAxios.get('/admin/grade/get?studentId='  + row.studentId)
    studentGrades.value = response

  } catch (error) {
    ElMessage.error('获取学生成绩失败：' + error.message)
    gradeDialogVisible.value = false
  }
}

// 获取成绩列表数据
const fetchGradeList = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const params = {
      ...searchForm,
      page: currentPage.value,
      size: pageSize.value
    }

    console.log(params)

    // 这里应该调用后端API
    const res = await myAxios.get("/admin/grade/list",{params})
    console.log(res)
    gradeList.value = res.records;
    total.value = res.total
  } catch (error) {
    ElMessage.error('获取成绩列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置页码到第一页
  fetchGradeList()
}

// 重置搜索条件
const resetSearch = () => {
  // 重置表单
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  currentPage.value = 1
  pageSize.value = 10
  fetchGradeList()
}

// 处理编辑成绩
const handleEdit = async (row) => {
  editDialogVisible.value = true
  currentStudent.value = row
  try {
    const response = await myAxios.get('/admin/grade/get?studentId=' + row.studentId)
    editGrades.value = response.map(grade => ({...grade}))
  } catch (error) {
    ElMessage.error('获取学生成绩失败：' + error.message)
    editDialogVisible.value = false
  }
}

// 添加成绩验证方法
const validateScore = (value, row) => {
  const score = parseInt(value)
  if (isNaN(score) || score < 0 || score > 100) {
    ElMessage.warning('成绩必须在0-100之间')
    row.score = ''
  }
}

// 添加提交成绩方法
const submitGrades = async () => {
  try {
    // 验证所有成绩
    const invalidScores = editGrades.value.some(grade => 
      !grade.score || isNaN(parseInt(grade.score)) || 
      parseInt(grade.score) < 0 || parseInt(grade.score) > 100
    )
    
    if (invalidScores) {
      ElMessage.warning('请确保所有成绩在0-100之间')
      return
    }

    await myAxios.post('/admin/grade/updateBatch', {
      studentId: currentStudent.value.studentId,
      gradeList: editGrades.value
    })

    ElMessage.success('成绩修改成功')
    editDialogVisible.value = false
    fetchGradeList() // 刷新列表
  } catch (error) {
    ElMessage.error('修改成绩失败：' + error.message)
  }
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchGradeList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchGradeList()
}

// 页面加载时获取数据
onMounted(() => {
  fetchGradeList()
  getOptions();
})

//获取选项
const getOptions = async () => {
  const res = await myAxios.get("/admin/grade/getOptions",{})
  console.log(res)
  semesterOptions.value = res.semesterOptions;
  classOptions.value = res.classNameOptions;
  courseOptions.value = res.courseNameOptions
}


</script>

<style scoped>
.grade-view {
  margin-top: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.fail-score {
  color: #f56c6c;
  font-weight: bold;
}

.history-operator {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.student-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.student-info p {
  margin: 8px 0;
}

.student-info strong {
  margin-right: 10px;
  color: #606266;
}

.fail-score {
  color: #f56c6c;
  font-weight: bold;
}
</style> 